<template>
  <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form :inline="true" :model="queryParams" ref="searchForm">
            <div class="search-form">
              <el-form-item>
                <el-button type="primary" icon="Plus" @click="handleAdd">添加搜索关键词</el-button>
                <el-button type="danger" v-if="selectIds.length > 0" icon="Delete" @click="handleBatchDels">批量回收站</el-button>
              </el-form-item>
              <el-form-item label="是否启用" prop="status">
                <el-select
                  v-model="queryParams.status"
                  @change="handleSearch"
                  class="m-2"
                  style="width:100px;"
                  placeholder="请选择启用状态"
                  clearable
                >
                  <el-option
                    v-for="item in [
                      { value: 1, label: '启用中' },
                      { value: 0, label: '禁止中' }
                    ]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="栏目名称" prop="keyword">
                <el-input v-model="queryParams.keyword" placeholder="请输入栏目名称..." maxlength="100" clearable />
              </el-form-item>
              <el-form-item>
                <el-button
                  style="padding: 16px !important"
                  type="primary"
                  :loading="tableLoading"
                  @click.prevent="handleSearch"
                  >查询</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button style="padding: 16px !important" @click.prevent="handleReset">重置</el-button>
                <el-button type="danger" icon="Delete" @click="handleOpenRecycle">
                  回收站
                </el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div class="draggable" style="background: #fff;">
          <el-table
            ref="tableRef"
            v-loading="tableLoading"
            :data="tableData"
            border
            row-key="id"
            :row-class-name="tableRowClassName"
            @selection-change="handleSelectionChange"
            height="calc(100vh - 310px)"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column fixed :label="'总数：' + total" width="100" align="center">
              <template v-slot="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="关键词"  align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.keyword" @blur="handleStatus(scope.row,'keyword')"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="排序"  align="center" width="200">
              <template v-slot="scope">
                <el-input-number v-model="scope.row.sortNum" class="txt-c" @blur="handleStatus(scope.row,'sortNum')"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180" align="center">
              <template #default="scope">
                <span>{{ formatTimeToStr(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="180" align="center">
              <template #default="scope">
                <span>{{ formatTimeToStr(scope.row.updateTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否启用"  width="180" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="handleStatus(scope.row, 'status')"
                  :active-value="1"
                  active-color="#4caf50"
                  active-text="启用中"
                  inactive-text="已禁止"
                  :inactive-value="0"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="200">
              <template #default="scope">
                <el-button icon="edit" type="primary" @click.stop="handleEdit(scope.row)">
                  编辑
                </el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="InfoFilled"
                  icon-color="#F90"
                  title="确定要删除此数据吗?"
                  @confirm="confirmEvent(scope.row)"
                >
                  <template #reference>
                    <el-button  icon="remove" type="danger"> 回收站 </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>

        <!-- 分页 -->
        <div class="kva-pagination-box center">
          <el-pagination
            :current-page="queryParams.pageNo"
            :page-size="queryParams.pageSize"
            :page-sizes="[100, 150, 200]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        </div>
      </home-page-header>
    </div>
    <add-keywords ref="addCategoryRef" @load="handleSearch"></add-keywords>
    <recycle-bin ref="recycleRef" @load="handleLodeData"></recycle-bin>
  </div>
</template>

<script setup>
  import KVA from '@/utils/kva.js'
  import { formatTimeToStr } from '@/utils/date.js'
  import AddKeywords from './components/AddKeywords.vue'
  import RecycleBin from './components/RecycleBin.vue'
  import {
    findPages,
    deleteById,
    bacthDeletes,
    updateStatus
  } from  '@/api/platform/searchkeywords.js'

  // 搜索属性定义
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 30,
    deleted: 0,
    status: '',
    newFlag:'',
    hotFlag:'',
    keyword: ''
  })

  // 定义响应式得列表数据容器
  const tableData = ref([])
  const tableLoading = ref(false)
  const pages = ref(0)
  const total = ref(0)
  const searchForm = ref({})
  // 批量删除
  const tableRef = ref({})
  const selectIds = ref([])
  // 编辑添加相关
  const addCategoryRef = ref({})
  const recycleRef = ref({})

  // 加载数据
  const handleLodeData = async () => {
    tableLoading.value = true
    const resp = await findPages(queryParams)
    tableLoading.value = false
    tableData.value = resp.data.records
    total.value = resp.data.total * 1
    pages.value = resp.data.pages * 1
  }

  // 打开回收站
  const handleOpenRecycle = () => {
    recycleRef.value.handleOpen()
  }

  // 搜索
  const handleSearch = () => {
    queryParams.pageNo = 1
    handleLodeData()
  }

  // 改变行颜色
  const tableRowClassName = ({ row, rowIndex }) => {
    if (row.loadmore == 1) {
      return 'hot-row'
    }
    return ''
  }

  // 重置
  const handleReset = () => {
    searchForm.value.resetFields()
    handleSearch()
  }

  // 分页size更改
  const handleSizeChange = (size) => {
    queryParams.pageSize = size
    handleLodeData()
  }

  // 分页pageNo更改
  const handleCurrentChange = (pno) => {
    queryParams.pageNo = pno
    handleLodeData()
  }

  // 添加事件
  const handleAdd = () => {
    addCategoryRef.value.handleOpen(null,tableData.value.length)
  }

  // 编辑
  const handleEdit = (row) => {
    addCategoryRef.value.handleOpen(row.id)
  }

  // 删除
  const handleDel = async (row) => {
    const opid = row.id
    await deleteById(opid)
    KVA.notifySuccess('删除成功!')
    handleLodeData()
  }

  const confirmEvent = async (row) => {
    await handleDel(row)
  }

  /**
   * 选择删除的元素
   * @param rows
   */
  const handleSelectionChange = (rows) => {
    selectIds.value = rows.map((c) => c.id)
  }

  // 更新状态
  const handleStatus = async (row, field) => {
    try {
      const res = await updateStatus(row.id, field, row[field])
      if (res.code == 20000) {
        KVA.notifySuccess('操作成功!')
        handleLodeData()
      }
    } catch (e) {
      console.log(e)
    }
  }


  /**
   * 批量加入回收站
   */
  const handleBatchDels = () => {
    if (selectIds.value && selectIds.value.length == 0) {
      KVA.notifyError('请选择一个项进行操作！')
      return
    }

    KVA.confirm('警告', '<strong>您确定要执行此次【批量加入回收站】操作吗？</strong>', { icon: 'success' }).then(
      async () => {
        const ids = selectIds.value.join(',')
        await bacthDeletes(ids)
        KVA.notifySuccess('批量恢复成功!')
        handleLodeData()
      }
    )
  }


  onMounted(async () => {
    await handleLodeData()
  })


</script>
<style>
  .el-table .hot-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
  }

  .diffBtn {
    --el-button-bg-color: #ff8310;
    --el-button-border-color: #ff8310;
  }
  .diffBtn:hover {
    --el-button-hover-border-color: #ff8310 !important;
    --el-button-hover-bg-color: #ff8310 !important;
  }
  .el-table tr td:nth-last-child(1) .cell {
    padding: 0;
  }
</style>
